package com.cskaoyan.config;

import com.cskaoyan.converter.String2DateConverter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

@Configuration
//@EnableWebMvc
//@ComponentScan("com.cskaoyan.controller")
public class WebConfiguration implements WebMvcConfigurer, ApplicationContextAware {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pic1/**").addResourceLocations("file:d:/spring/");
    }

    /*@Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2DateConverter());
    }*/

    @Override
    public void addFormatters(FormatterRegistry registry) {
        //把所有的Converter组件都找出来
        Map<String, Converter> beansOfType = applicationContext.getBeansOfType(Converter.class);
        Collection<Converter> values = beansOfType.values();
        Iterator<Converter> iterator = values.iterator();
        //根据value（Converter）做遍历
        if (iterator.hasNext()) {
            Converter converter = iterator.next();
            registry.addConverter(converter);
        }
        //registry.addConverter();
    }
    ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
